package afss.freesky.util;

import java.util.Properties;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class JNDITest {

	public String accountName = "cn=sysman,ou=eclipseusers,ou=eclipse,dc=GiEclipseAdam,dc=com";
	public String accountPwd = "sysman";

	/**
	 * 从连接池中获取一个连接.
	 * 
	 * @return LdapContext
	 * @throws NamingException
	 */
	public LdapContext getConnectionFromFool() throws NamingException {
		Properties env = new Properties();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, "ldap://wswincnhz0392:50000");
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		env.put(Context.SECURITY_PRINCIPAL, accountName);
		env.put(Context.SECURITY_CREDENTIALS, accountPwd);
		env.put("com.sun.jndi.ldap.connect.pool", "true");
		env.put("java.naming.referral", "follow");
		return new InitialLdapContext(env, null);
	}

	/**
	 * 校验用户登录.
	 * 
	 * @param userDn
	 *            String
	 * @param password
	 *            String
	 * @return boolean
	 */
	public boolean authenticate(String userDn, String password) {
		LdapContext ctx = null;
		try {
			Control[] connCtls = new Control[] {};
			ctx = getConnectionFromFool();
			ctx.getRequestControls();
			ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDn);
			ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
			ctx.reconnect(connCtls);
			return true;
		} catch (AuthenticationException e) {
			return false;
		} catch (NamingException e) {
			return false;
		} finally {
			if (ctx != null) {
				try {
					ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, accountName);
					ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, accountPwd);
					ctx.reconnect(ctx.getConnectControls());
					ctx.close();
				} catch (NamingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ctx = null;
			}
		}
	}

	/**
	 * 修改用户信息.
	 * 
	 * @param attrs
	 *            Attributes 需要修改的用户属性.
	 * @param userDN
	 *            String 用户DN
	 * @return
	 */
	public NamingEnumeration load(String searchBase, String returnedAtts[]) {
		LdapContext ctx = null;
		NamingEnumeration answer = null;
		try {
			ctx = getConnectionFromFool();
			SearchControls searchCtls = new SearchControls();
			searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
			String searchFilter = "objectClass=top";
			searchCtls.setReturningAttributes(returnedAtts);
			answer = ctx.search(searchBase, searchFilter, searchCtls);
			return answer;
		} catch (NamingException e) {
			System.err.println("Problem changing password: " + e);
		} catch (Exception e) {
			System.err.println("Problem: " + e);
		} finally {
			if (ctx != null) {
				try {
					ctx.close();
				} catch (NamingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ctx = null;
			}
		}
		return answer;
	}

	/**
	 * 修改用户信息.
	 * 
	 * @param attrs
	 *            Attributes 需要修改的用户属性.
	 * @param userDN
	 *            String 用户DN
	 * @return
	 */
	public boolean modify(Attributes attrs, String userDN) {
		LdapContext ctx = null;
		try {
			ctx = getConnectionFromFool();
			ctx.modifyAttributes(userDN, DirContext.REPLACE_ATTRIBUTE, attrs);
			return true;
		} catch (NamingException e) {
			System.err.println("Problem changing password: " + e);
		} catch (Exception e) {
			System.err.println("Problem: " + e);
		} finally {
			if (ctx != null) {
				try {
					ctx.close();
				} catch (NamingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ctx = null;
			}
		}
		return false;
	}

	/**
	 * 修改用户信息.
	 * 
	 * @param attrs
	 *            Attributes 需要修改的用户属性.
	 * @param userDN
	 *            String 用户DN
	 * @return
	 */
	public boolean modifyPwd(String userDN, String pwd) {
		LdapContext ctx = null;
		try {
			ctx = getConnectionFromFool();
			ModificationItem[] mods = new ModificationItem[1];
			mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userPassword", pwd));
			ctx.modifyAttributes(userDN, mods);
			return true;
		} catch (NamingException e) {
			System.err.println("Problem changing password: " + e);
		} catch (Exception e) {
			System.err.println("Problem: " + e);
		} finally {
			if (ctx != null) {
				try {
					ctx.close();
				} catch (NamingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ctx = null;
			}
		}
		return false;
	}

	/**
	 * 添加用户.
	 * 
	 * @param userDN
	 *            String用户DN
	 * @param userName
	 *            String 用户登录名
	 * @param userPwd
	 *            String 用户密码
	 * @return boolean 添加是否成功.
	 */
	public boolean addUser(String userDN, String userName, String userPwd) {
		LdapContext ctx = null;
		try {
			ctx = getConnectionFromFool();
			// Create attributes to be associated with the new user
			Attributes attrs = new BasicAttributes(true);
			// These are the mandatory attributes for a user object
			// Note that Win2K3 will automagically create a random
			// samAccountName if it is not present. (Win2K does not)
			attrs.put("objectClass", "user");
			attrs.put("name", userName);
			attrs.put("cn", userName);

			// Create the context
			ctx.createSubcontext(userDN, attrs);
			ModificationItem[] mods = new ModificationItem[1];
			mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userPassword", userPwd));
			// Perform the update
			ctx.modifyAttributes(userDN, mods);
			mods = null;
			return true;
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			if (ctx != null) {
				try {
					ctx.close();
				} catch (NamingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ctx = null;
			}
		}
		return false;
	}

	/**
	 * 删除用户.
	 * 
	 * @param userDN
	 *            String 用户DN
	 * @return
	 */
	public boolean delUser(String userDN) {
		LdapContext ctx = null;
		try {
			ctx = getConnectionFromFool();
			ctx.destroySubcontext(userDN);
			return true;
		} catch (NamingException e) {
			System.err.println("Problem changing password: " + e);
		} catch (Exception e) {
			System.err.println("Problem: " + e);
		} finally {
			if (ctx != null) {
				try {
					ctx.close();
				} catch (NamingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ctx = null;
			}
		}
		return false;
	}
}
